package com.lineage.echo;

import com.lineage.config.ConfigOther;
import com.lineage.data.event.OnlineGiftSet;
import com.lineage.server.datatables.GetbackTable;
import com.lineage.server.datatables.lock.AccountReading;
import com.lineage.server.datatables.lock.shop_lxReading;
import com.lineage.server.model.Instance.L1DollInstance;
import com.lineage.server.model.Instance.L1FollowerInstance;
import com.lineage.server.model.Instance.L1IllusoryInstance;
import com.lineage.server.model.Instance.L1NpcInstance;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.model.Instance.L1PetInstance;
import com.lineage.server.model.Instance.L1SkinInstance;
import com.lineage.server.model.Instance.L1SummonInstance;
import com.lineage.server.model.L1Clan;
import com.lineage.server.model.L1Trade;
import com.lineage.server.serverpackets.S_Disconnect;
import com.lineage.server.serverpackets.S_PacketBox;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.templates.L1Account;
import com.lineage.server.world.World;
import com.lineage.server.world.WorldClan;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class QuitGame {
  private static final Log _log = LogFactory.getLog(QuitGame.class);
  
  public static void quitGame(L1PcInstance pc) {
    if (pc == null)
      return; 
    if (pc.getOnlineStatus() == 0)
      return; 
    L1Clan clan = WorldClan.get().getClan(pc.getClanname());
    if (clan != null && clan.getWarehouseUsingChar() == pc.getId())
      clan.setWarehouseUsingChar(0); 
    if (!pc.getPetList().isEmpty()) {
      Object[] petList = pc.getPetList().values().toArray();
      if (petList != null)
        remove_pet(pc, petList); 
    } 
    try {
      if (!pc.getDolls().isEmpty()) {
        Object[] dolls = pc.getDolls().values().toArray();
        Object[] array;
        int n = (array = dolls).length;
        int i = 0;
        while (i < n) {
          Object obj = array[i];
          L1DollInstance doll = (L1DollInstance)obj;
          if (doll != null)
            doll.deleteDoll(); 
          i++;
        } 
        pc.getDolls().clear();
      } 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
    try {
      if (pc.getHierarchs() != null)
        pc.getHierarchs().deleteHierarch(); 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
    try {
      if (!pc.get_otherList().get_illusoryList().isEmpty()) {
        Object[] illList = pc.get_otherList().get_illusoryList().values().toArray();
        Object[] array;
        int n = (array = illList).length;
        int i = 0;
        while (i < n) {
          Object obj = array[i];
          L1IllusoryInstance ill = (L1IllusoryInstance)obj;
          if (ill != null)
            ill.deleteMe(); 
          i++;
        } 
      } 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
    try {
      pc.get_otherList().clearAll();
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
    try {
      if (pc.isDead()) {
        int[] loc = GetbackTable.GetBack_Location(pc, true);
        pc.setX(loc[0]);
        pc.setY(loc[1]);
        pc.setMap((short)loc[2]);
        pc.setCurrentHp(pc.getLevel());
        if (pc.get_food() > 40)
          pc.set_food(40); 
      } 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
    try {
      if (pc.getTradeID() != 0) {
        L1Trade trade = new L1Trade();
        trade.tradeCancel(pc);
      } 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
    try {
      if (pc.getFightId() != 0) {
        pc.setFightId(0);
        L1PcInstance fightPc = (L1PcInstance)World.get().findObject(pc.getFightId());
        if (fightPc != null) {
          fightPc.setFightId(0);
          fightPc.sendPackets((ServerBasePacket)new S_PacketBox(5, 0, 0));
        } 
      } 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
    try {
      if (pc.isInParty())
        pc.getParty().leaveMember(pc); 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
    try {
      if (pc.isInChatParty())
        pc.getChatParty().leaveMember(pc); 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
    try {
      if (!pc.getFollowerList().isEmpty()) {
        Object[] followerList = pc.getFollowerList().values().toArray();
        Object[] array;
        int n = (array = followerList).length;
        int i = 0;
        while (i < n) {
          Object obj = array[i];
          L1FollowerInstance follower = (L1FollowerInstance)obj;
          follower.setParalyzed(true);
          follower.spawn(follower.getNpcTemplate().get_npcId(), follower.getX(), follower.getY(), 
              follower.getHeading(), follower.getMapId());
          follower.deleteMe();
          i++;
        } 
      } 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
    try {
      if (ConfigOther.Quitgameshop) {
        L1Account acc = AccountReading.get().getAccount(pc.getAccountName());
        String mac = null;
        if (acc.get_mac() != null)
          mac = acc.get_mac(); 
        if (pc.isPrivateShop() && !shop_lxReading.get().isExist(mac)) {
          OnlineGiftSet.remove(pc);
          pc.save();
          pc.saveInventory();
          shop_lxReading.get().updatemejs(pc.getId(), pc.getName());
          pc.sendPackets((ServerBasePacket)new S_Disconnect());
          return;
        } 
      } 
      pc.stopEtcMonitor();
      pc.setOnlineStatus(0);
      pc.save();
      pc.saveInventory();
      pc.logout();
      if (pc.getSkins() != null) {
        Map<Integer, L1SkinInstance> skinList = pc.getSkins();
        Iterator<Integer> iterator = skinList.keySet().iterator();
        while (iterator.hasNext()) {
          Integer gfxid = iterator.next();
          pc.getSkin(gfxid.intValue()).deleteMe();
        } 
      } 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
  
  private static void remove_pet(L1PcInstance pc, Object[] petList) {
    try {
      int length = petList.length;
      int i = 0;
      while (i < length) {
        Object obj = petList[i];
        L1NpcInstance petObject = (L1NpcInstance)obj;
        if (petObject != null) {
          if (petObject instanceof L1PetInstance) {
            L1PetInstance pet = (L1PetInstance)petObject;
            pet.collect(true);
            pc.removePet((L1NpcInstance)pet);
            pet.deleteMe();
          } 
          if (petObject instanceof L1SummonInstance) {
            L1SummonInstance summon = (L1SummonInstance)petObject;
            if (summon != null) {
              if (summon.destroyed())
                return; 
              summon.Death(null);
            } 
          } 
        } 
        i++;
      } 
      pc.getPetList().clear();
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
}
